package com.dushuren.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dushuren.project.common.BaseResponse;
import com.dushuren.project.common.ResultUtils;
import com.dushuren.project.model.dto.SearchWordsAddRequest;
import com.dushuren.project.model.dto.SearchWordsDeleteRequest;
import com.dushuren.project.model.dto.SearchWordsRequest;
import com.dushuren.project.model.dto.SearchWordsUpdateRequest;
import com.dushuren.project.model.entity.RecordWordsSearch;
import com.dushuren.project.model.entity.SuggestNotWordsSearch;
import com.dushuren.project.model.entity.SuggestWordsSearch;
import com.dushuren.project.model.enums.SuggestSearchSelectEnum;
import com.dushuren.project.model.vo.SuggestWordsSearchVo;
import com.dushuren.project.model.vo.UserVo;
import com.dushuren.project.service.RecordWordsSearchService;
import com.dushuren.project.service.SuggestNotWordsSearchService;
import com.dushuren.project.service.SuggestWordsSearchService;
import com.dushuren.project.service.UserService;
import com.dushuren.project.utils.RedisUtils;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.ParameterModeHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import static com.dushuren.project.constant.SearchConstant.STORAGE_SEARCH;

@RestController
@RequestMapping("/search")
@Slf4j
public class SearchController {

  @Resource
  UserService userService;


  @Resource
  SuggestWordsSearchService suggestWordsSearchService;

  @Resource
  RedisUtils redisUtils;

  @Resource
  SuggestNotWordsSearchService suggestNotWordsSearchService;

  @Resource
  RecordWordsSearchService recordWordsSearchService;


  /**
   * 获取 搜索推荐结果 search
   */
  @GetMapping("/list")
  public BaseResponse<Page<SuggestWordsSearchVo>> listSuggestWordsSearch(HttpServletRequest request) {
	UserVo isServletRequest = userService.getIsServletRequest(request);
	Integer userRole = isServletRequest.getUserRole();
	Gson gson = new Gson();
	String listSearch = (String) redisUtils.get(STORAGE_SEARCH);
	// todo 为什么使用 redis 读取了 速度还是没有什么提升
	if (listSearch != null) {
	  return ResultUtils.success(gson.fromJson(listSearch, new Page<SuggestWordsSearchVo>().getClass()));
	}

	QueryWrapper<SuggestWordsSearch> queryWrapper = new QueryWrapper<>();
	queryWrapper.select(SuggestSearchSelectEnum.getValues().toArray(new String[0]));
	queryWrapper.orderByDesc("searchFirst");
	Page<SuggestWordsSearch> page = suggestWordsSearchService.page(new Page<>(1,20), queryWrapper);

	List<SuggestWordsSearchVo> resultSorted = page.getRecords().stream().map(suggestWordsSearch -> {
	  SuggestWordsSearchVo suggestWordsSearchVo = new SuggestWordsSearchVo();
	  BeanUtils.copyProperties(suggestWordsSearch, suggestWordsSearchVo);
	  // 管理员可见信息
	  if (userRole != 1) {
		suggestWordsSearchVo.setSearchFirst(null);
		suggestWordsSearchVo.setSearchNumber(null);
	  }
	  return suggestWordsSearchVo;
	}).collect(Collectors.toList());

	Page<SuggestWordsSearchVo> pageVo = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
	pageVo.setRecords(resultSorted);


	// todo 写入redis缓存
	redisUtils.set(STORAGE_SEARCH, gson.toJson(pageVo), 30000L);
	return ResultUtils.success(pageVo);
  }

  /**
   * 管理员  查询所有 类型 搜素词
   */
  @GetMapping("/list/all")
  public BaseResponse<Page<SuggestWordsSearchVo>> queryAllSearchWords(SearchWordsRequest searchWordsRequest , HttpServletRequest request) {
	userService.isAdministrators(request);
	Long searchCategory = searchWordsRequest.getSearchCategory();

	if (searchCategory == null) {
	  searchCategory = 0L;
	}
	Page<SuggestWordsSearchVo> page = null;
	 // 查询对应的数据值
	if (searchCategory == 0) {
	  // 查询推荐
	  page = suggestWordsSearchService.queryListData(searchWordsRequest);
	} else if (searchCategory == 1) {
	  // 查询不推荐
	  page = suggestNotWordsSearchService.queryListData(searchWordsRequest);
	} else if (searchCategory == 2) {
	  // 查询 所有监听词
	  page = recordWordsSearchService.queryListData(searchWordsRequest);
	} else {
	  page = new Page<>();
	}
	return ResultUtils.success(page);
  }

  /**
   * 删除 指定对应的 搜索词
   */
  @PostMapping("/delete")
  public BaseResponse<Long> deleteSearchWords(@RequestBody SearchWordsDeleteRequest searchWordsDeleteRequest, HttpServletRequest request) {
	userService.isAdministrators(request);
	Long id = searchWordsDeleteRequest.getId();
	Long searchCategory = searchWordsDeleteRequest.getSearchCategory();
	Long result;

	if (searchCategory == 0) {
	// 删除推荐
	  result = suggestWordsSearchService.deleteSearchWords(id);
	  callbackCache();
	} else if (searchCategory == 1) {
	// 删除不推荐
	  result = suggestNotWordsSearchService.deleteSearchWords(id);
	} else if (searchCategory == 2) {
	// 删除 所有监听词
	  result = recordWordsSearchService.deleteSearchWords(id);
	} else {
	  result = 0L;
	}
	return ResultUtils.success(result);
  }


  /**
   * 修改 指定对应的 搜索词
   */
  @PostMapping("/update")
  public BaseResponse<Long> updateSearchWords(@RequestBody SearchWordsUpdateRequest searchWordsUpdateRequest, HttpServletRequest request) {
	userService.isAdministrators(request);
	Long searchCategory = searchWordsUpdateRequest.getSearchCategory();
	Long result;
	Long id = searchWordsUpdateRequest.getId();
	String searchInformation = searchWordsUpdateRequest.getSearchInformation();
	Integer searchNumber = searchWordsUpdateRequest.getSearchNumber();

	if (searchCategory == 0) {
	  SuggestWordsSearch suggestWordsSearch = new SuggestWordsSearch();
	  suggestWordsSearch.setId(id);
	  suggestWordsSearch.setSearchInformation(searchInformation);
	  suggestWordsSearch.setSearchNumber(searchNumber);
	  Long searchFirst = searchWordsUpdateRequest.getSearchFirst();
	  suggestWordsSearch.setSearchFirst(searchFirst);
	  // 修改 推荐
	  result = suggestWordsSearchService.updateSearchWords(suggestWordsSearch);
	  callbackCache();
	} else if (searchCategory == 1) {
	  SuggestNotWordsSearch suggestNotWordsSearch = new SuggestNotWordsSearch();
	  suggestNotWordsSearch.setId(id);
	  suggestNotWordsSearch.setSearchInformation(searchInformation);
	  suggestNotWordsSearch.setSearchNumber(searchNumber);
	  // 修改 不推荐
	  result = suggestNotWordsSearchService.updateSearchWords(suggestNotWordsSearch);
	} else if (searchCategory == 2) {
	  RecordWordsSearch recordWordsSearch = new RecordWordsSearch();
	  recordWordsSearch.setId(id);
	  recordWordsSearch.setSearchInformation(searchInformation);
	  Long userId = searchWordsUpdateRequest.getUserId();
	  recordWordsSearch.setUserId(userId);
	  // 修改 监听词
	  result = recordWordsSearchService.updateSearchWords(recordWordsSearch);
	} else {
	  result = 0L;
	}

	return ResultUtils.success(result);
  }

  /**
   * 增加 指定推荐
   */
  @PostMapping("/add")
  public BaseResponse<Long> addSearchWords(@RequestBody SearchWordsAddRequest searchWordsAddRequest, HttpServletRequest request) {
	userService.isAdministrators(request);
	Long searchCategory = searchWordsAddRequest.getSearchCategory();
	String searchInformation = searchWordsAddRequest.getSearchInformation();
	Integer searchNumber = searchWordsAddRequest.getSearchNumber();
	Long result;

	if (searchCategory == 0) {
	  SuggestWordsSearch suggestWordsSearch = new SuggestWordsSearch();
	  suggestWordsSearch.setSearchInformation(searchInformation);
	  suggestWordsSearch.setSearchNumber(searchNumber);
	  Long searchFirst = searchWordsAddRequest.getSearchFirst();
	  suggestWordsSearch.setSearchFirst(searchFirst);
	  // 增加 推荐
	  result = suggestWordsSearchService.addSearchWords(suggestWordsSearch);
	  callbackCache();
	} else if (searchCategory == 1) {
	  SuggestNotWordsSearch suggestNotWordsSearch = new SuggestNotWordsSearch();
	  suggestNotWordsSearch.setSearchInformation(searchInformation);
	  suggestNotWordsSearch.setSearchNumber(searchNumber);
	  // 增加 不推荐
	  result = suggestNotWordsSearchService.addSearchWords(suggestNotWordsSearch);
	} else if (searchCategory == 2) {
	  RecordWordsSearch recordWordsSearch = new RecordWordsSearch();
	  recordWordsSearch.setSearchInformation(searchInformation);
	  Long userId = searchWordsAddRequest.getUserId();
	  recordWordsSearch.setUserId(userId);
	  // 增加 监听词
	  result = recordWordsSearchService.addSearchWords(recordWordsSearch);
	} else {
	  result = 0L;
	}

	return ResultUtils.success(result);
  }


  /**
   * 删除缓存
   */
  public void callbackCache(){
	redisUtils.remove(STORAGE_SEARCH);
  }

}
